import os

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt


def analysis( df, symbol):
    # 计算最终收益率
    final_return = df['return_sum'].iloc[-1]
    print(f"最终收益率: {final_return:.2%}")

    # 计算最大回撤
    df['peak'] = df['return_sum'].cummax()
    df['drawdown'] = df['peak'] - df['return_sum']
    max_drawdown = df['drawdown'].max()
    print(f"最大回撤: {max_drawdown:.2%}")

    # 计算波动率
    volatility = df['return'].std() * np.sqrt(252)  # 假设每年有252个交易日
    print(f"波动率: {volatility:.2%}")

    return [symbol, final_return, max_drawdown, volatility]


# main
if __name__ == '__main__':
    # 设置文件夹路径
    folder_path = 'Step6Data'

    # 获取文件夹中所有的CSV文件
    csv_files = [f for f in os.listdir(folder_path) if f.endswith('.csv')]



    all_analysis=[]
    # 遍历每个CSV文件
    for file in csv_files:
        # 构造文件路径
        file_path = os.path.join(folder_path, file)

        # 读取CSV文件
        df = pd.read_csv(file_path)

        # 假设CSV文件中包含两列：日期（Date）和收盘价（Close）
        # 计算每日涨跌幅
        df['return']=df['close'].pct_change()

        # 累计涨跌幅的序列
        initial_price = df['close'].iloc[0]
        df['return_sum'] = (df['close'] - initial_price) / initial_price

        df_new = pd.DataFrame()

        df_new['close'] = df['close']
        df_new['return'] = df['return']
        df_new['return_sum'] = df['return_sum']

        res=analysis(df_new,file.split('_')[0])
        all_analysis.append(res)
    print(all_analysis)
    # 转换为 DataFrame
    columns = ['Stock Code', 'Final Return', 'Max Drawdown', 'Volatility']
    df = pd.DataFrame(all_analysis, columns=columns)
    #show df by pandasgui
    # import pandasgui
    # pandasgui.show(df)
    print(df)
    #df to csv,name Step6.csv
    df.to_csv('Step6.csv')


